<template>
  <div v-loading="loadings" class="app-container">
    <!-- 项目基础信息 -->
    <h5 class="titleInfo">项目基础信息</h5>
    <el-form ref="form" :model="form" :rules="rules" label-width="130px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目关键字">
            <el-input v-model="form.keyword" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目分类" prop="cates">
            <el-cascader
              v-model="form.cates"
              placeholder="请选择"
              :options="cateOption"
              change-on-select
              show-all-levels
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="医院名称" prop="hospitalId">
            <el-select v-model="form.hospitalId" filterable placeholder="请选择">
              <el-option
                v-for="item in hosOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="擅长医生">
            <el-select
              v-model="form.doctors"
              multiple
              placeholder="请选择"
              @click.native="getDoctorList()"
            >
              <el-option
                v-for="item in docOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="简介">
            <el-input v-model="form.descript" />
          </el-form-item>
        </el-col>
        <!-- 新增项目标签 -->
        <el-col :span="12">
          <el-form-item label="项目标签">
            <el-select v-model="form.tagsId" placeholder="请选择">
              <el-option
                v-for="item in mmkTagsOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 项目特色 -->
      <div class="divBar" />
      <h5 class="titleInfo">
        项目特色
        <span style="font-size:12px;margin-left: 12px;color: #606266;">当保险服务选择为是时，项目保障必须填写</span>
      </h5>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否维护">
            <el-select v-model="form.isRepair" placeholder="请选择">
              <el-option
                v-for="item in repOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="保险服务">
            <el-select v-model="form.insuranceIsSet" placeholder="请选择">
              <el-option
                v-for="item in insOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="ensureFlag" :span="12">
          <el-form-item label="项目保障" prop="ensureContent">
            <el-select
              v-model="form.ensureContent"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择"
            >
              <el-option
                v-for="item in ensOptions"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 项目价格信息 -->
      <div class="divBar" />
      <h5 class="titleInfo">项目价格信息</h5>
      <el-row>
        <el-col :span="12">
          <el-form-item label="购买方式" prop="projectType">
            <el-select v-model="form.projectType" placeholder="请选择">
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <div v-if="priceSH">
          <el-col :span="12">
            <el-form-item label="预约价格" prop="appointmentPrice">
              <el-input v-model="form.appointmentPrice" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优惠价格范围起" prop="discountsRangeB">
              <el-input v-model="form.discountsRangeB" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优惠价格范围止" prop="discountsRangeE">
              <el-input v-model="form.discountsRangeE" @blur="discBlur" />
            </el-form-item>
          </el-col>
        </div>
        <div v-else>
          <el-col :span="12">
            <el-form-item label="项目全款价" prop="projectPrice">
              <el-input v-model="form.projectPrice" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抵扣金银币" prop="deductionMethod">
              <el-select v-model="form.deductionMethod" placeholder="请选择">
                <el-option label="不抵扣" value="0"></el-option>
                <el-option label="抵扣金币" value="1"></el-option>
                <el-option label="抵扣银币" value="2"></el-option>
              </el-select>
              <el-input v-if="form.deductionMethod !=0" v-model="form.deductionCredit" />
            </el-form-item>
          </el-col>
        </div>
        <el-col :span="12">
          <el-form-item label="原价" prop="originPrice">
            <el-input v-model="form.originPrice" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优惠价" prop="discounts">
            <el-input v-model="form.discounts" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目预约量">
            <el-input v-model="form.appointmentPeoples" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input v-model="form.sort" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 项目显示状态 -->
      <div class="divBar" />
      <!-- <loadImg></loadImg> -->
      <h5 class="titleInfo">项目显示状态</h5>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否上架">
            <el-select v-model="form.status" placeholder="请选择">
              <el-option
                v-for="item in staOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="推荐首页">
            <el-select v-model="form.isDashboard" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 项目材料管理 -->
      <div class="divBar" />
      <h5 class="titleInfo">项目材料管理</h5>
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目图片">
            <newUpload
              ref="uploadImg1"
              :file-list="fileList1"
              :file-num="1"
              :width="750"
              :height="750"
            />
            <p>尺寸为 750 * 750 px</p>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="项目图册">
            <newUpload
              ref="uploadImg2"
              :file-list="fileList"
              :file-num="4"
              :width="750"
              :height="750"
            />
            <p>尺寸为 750 * 750 px</p>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="项目描述">
            <Tinymce v-model="form.content" style="width:96%" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button
          style="margin:30px 0"
          type="primary"
          @click="submitFn('form')"
          v-if="$route.name =='itemEdit'"
        >立即提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import newUpload from "@/components/imgUpload/index";
import Tinymce from "@/components/Tinymce";
import { hospitalDropDown } from "@/api/doctorManage";
import {
  doctorList,
  insertProject,
  updateProject,
  findProjectByProjectId,
  MmkTagsList
} from "@/api/itemList";
import { findProjectGuaranteeList } from "@/api/itemSecurity";
import { findAllBeautyCategoryList } from "@/api/medicalClassifyList";
import { async } from "q";

export default {
  name: "ItemEdit",
  components: { Tinymce, newUpload },
  data() {
    // 正整数
    var numberReg = (rule, value, callback) => {
      const reg = /^\d{1,}$/;

      if (!value) {
        callback(new Error("请输入优惠价范围"));
      } else if (value && !reg.test(value)) {
        callback(new Error("请输入0以上的正整数"));
      } else {
        callback();
      }
    };
    return {
      mmkTagsOptions: [],
      loadings: true,
      ensureFlag: false,
      fileList1: [],
      fileNum1: 1,
      imgUploadFlag: true,
      fileList: [],
      fileNum: 4,
      content: "",
      value1: "",
      options: [
        {
          value: "0",
          label: "否"
        },
        {
          value: "1",
          label: "是"
        }
      ],
      priceSH: true,
      proOptions: [],
      cates: [],
      form: {
        deductionMethod: "0",
        projectId: null,
        name: null,
        keyword: null,
        tagsId: null,
        // promotionsId:null,
        hospitalId: null,
        cates: null,
        doctors: null,
        descript: "",
        isRepair: "0",
        insuranceIsSet: "1",
        ensureContent: null,
        projectType: "0",
        appointmentPrice: "0",
        discountsRangeB: "",
        discountsRangeE: "",
        projectPrice: "0",
        deductionCredit: "0",
        originPrice: null,
        discounts: null,
        appointmentPeoples: null,
        sort: null,
        status: null,
        isDashboard: null,
        projectImages: [],
        pBcId: null,
        content: ""
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入项目名称",
            trigger: "blur"
          }
        ],
        cates: [
          {
            required: true,
            message: "请选择项目分类",
            trigger: "blur"
          }
        ],
        hospitalId: [
          {
            required: true,
            message: "请选择医院名称",
            trigger: "blur"
          }
        ],
        projectType: [
          {
            required: true,
            message: "请选择购买方式",
            trigger: "blur"
          }
        ],
        appointmentPrice: [
          {
            required: true,
            message: "请输入预约价格",
            trigger: "blur"
          }
        ],
        projectPrice: [
          {
            required: true,
            message: "请输入项目全款价",
            trigger: "blur"
          }
        ],
        deductionMethod: [
          {
            required: true,
            message: "请输入抵扣积分",
            trigger: "blur"
          }
        ],
        originPrice: [
          { required: true, message: "请输入原价", trigger: "blur" }
        ],
        discounts: [
          { required: true, message: "请输入优惠价", trigger: "blur" }
        ],
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
        ensureContent: [
          {
            required: true,
            message: "请选择项目保障",
            trigger: "blur"
          }
        ],
        discountsRangeB: [
          { required: true, validator: numberReg, trigger: "blur" }
        ],
        discountsRangeE: [
          { required: true, validator: numberReg, trigger: "blur" }
        ]
      },
      hosOptions: [],
      docOptions: [],
      repOptions: [
        {
          value: "0",
          label: "否"
        },
        {
          value: "1",
          label: "是"
        }
      ],
      insOptions: [
        {
          value: "1",
          label: "否"
        },
        {
          value: "2",
          label: "是"
        }
      ],
      typeOptions: [
        {
          value: "0",
          label: "预约项目"
        },
        {
          value: "1",
          label: "全额购买项目"
        }
      ],
      staOptions: [
        {
          value: "0",
          label: "上线"
        },
        {
          value: "1",
          label: "下线"
        },
        {
          value: "2",
          label: "回收站"
        }
      ],
      ensOptions: [],
      cateOption: [
        {
          value: 0,
          label: "医美"
        },
        {
          value: 1,
          label: "口腔管理"
        },
        {
          value: 2,
          label: "健康管理"
        }
      ],
      userId: ""
    };
  },
  watch: {
    "form.projectType"(val) {
      if (this.form.projectType == "0") {
        this.priceSH = true;
      } else {
        this.priceSH = false;
      }
    },
    "form.insuranceIsSet"(val) {
      if (val == "2") {
        this.ensureFlag = true;
      } else {
        this.ensureFlag = false;
      }
    }
  },
  created() {
    // 获取项目标签
    this.MmkTagsList();
    this.cateOption = JSON.parse(localStorage.getItem("cate"));
    this.getDrop();
  },
  mounted() {
    this.userId = this.$route.query.userId + "";
    this.getInfo();
    this.getDoctorList();
    this.form.projectId = Number(this.userId);
    // console.log(this.form)
  },
  methods: {
    // 获取项目标签
    MmkTagsList() {
      const datas = { id: 5 };
      MmkTagsList(datas)
        .then(res => {
          if (res.data.code == 0) {
            console.log("tags", res);
            const resData = res.data.data;
            resData.forEach(item => {
              this.mmkTagsOptions.push({
                value: Number(item.id),
                label: item.name
              });
            });
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch(error => {
          this.$message.error(error);
        });
    },
    discBlur() {
      if (
        Number(this.form.discountsRangeE) < Number(this.form.discountsRangeB)
      ) {
        this.$message({
          message: "优惠价格范围止不能小于优惠价格范围起",
          type: "warning"
        });
        this.form.discountsRangeE = "";
      }
    },
    getInfo() {
      this.loadings = true;
      const datas = {
        id: this.userId
      };
      findProjectByProjectId(datas).then(res => {
        this.form = res.data.data;
        //  console.log(this.form);
        this.form.insuranceIsSet = this.form.insuranceIsSet + "";
        this.form.isRepair = this.form.isRepair + "";
        this.form.projectType = this.form.projectType + "";
        this.form.status = this.form.status + "";
        this.form.isDashboard = this.form.isDashboard + "";
        if (this.form.ensureContent != "0" && this.form.insuranceIsSet == "2") {
          this.form.ensureContent = this.form.ensureContent.split(",");
        } else {
          this.form.ensureContent = [];
        }
        if (res.data.data) {
          this.form.discountsRangeB = res.data.data.discountsRange.split(
            "~"
          )[0];
          this.form.discountsRangeE = res.data.data.discountsRange.split(
            "~"
          )[1];
        } else {
          this.form.discountsRangeB = "";
          this.form.discountsRangeE = "";
        }
        if (this.form.doctors) {
          this.form.doctors = this.form.doctors.map(Number);
        } else {
          this.form.doctors = [];
        }
        if (this.form.pBcId && !this.tableLoading) {
          this.form.cates = this.form.pBcId.split("/").map(Number);
        } else {
          this.form.cates = [];
        }
        if (res.data.data.projectImages) {
          res.data.data.projectImages.forEach((e, index) => {
            this.fileList.push({
              url:
                localStorage.getItem("imgUrlPrefix") +
                res.data.data.projectImages[index]
            });
          });
        }
        if (res.data.data.image) {
          this.fileList1 = [
            {
              url: localStorage.getItem("imgUrlPrefix") + res.data.data.image
            }
          ];
        }
        this.form = JSON.parse(JSON.stringify(this.form));
      });
    },

    getDoctorList() {
      const datas = {
        hospitalId: this.form.hospitalId + "",
        pageNum: "1",
        pageSize: "10000"
      };
      doctorList(datas).then(res => {
        // console.log(res)
        const resData = res.data.data.list;
        const newData = [];
        resData.forEach(e => {
          newData.push({
            value: e.id,
            label: e.name
          });
        });
        this.docOptions = newData;
      });
    },
    // 获取相关下拉列表
    getDrop() {
      // 医院列表
      hospitalDropDown()
        .then(res => {
          const resData = res.data.data;
          const newData = [];
          resData.forEach(e => {
            newData.push({
              value: e.id,
              label: e.name
            });
          });
          this.loadings = false;
          this.hosOptions = newData;
        })
        .catch(error => {
          this.loadings = false;
          this.$message.error(error);
        });
      // 项目保障
      const datas1 = {
        pageNum: "0",
        pageSize: "10000"
      };
      findProjectGuaranteeList(datas1).then(res => {
        const resData = res.data.data.list;
        const newData = [];
        resData.forEach(e => {
          newData.push({
            value: e.id,
            label: e.name
          });
        });
        this.ensOptions = newData;
        // console.log(newData)
      });
    },
    updatafn(datas) {
      updateProject(datas).then(res => {
        this.datafn(res);
      });
    },
    datafn(res) {
      this.$message({
        showClose: true,
        message: res.data.msg,
        type: "warning"
      });
      if (res.data.code == 0) {
        this.$router.push("/itemIndex");
      }
    },
    createfn(datas) {
      insertProject(datas).then(res => {
        this.datafn(res);
      });
    },
    // 修改提交
    submitFn(e) {
      this.$refs[e].validate(valid => {
        if (valid) {
          if (
            this.form.deductionMethod != 0 &&
            this.form.deductionCredit == 0
          ) {
            this.$message({
              showClose: true,
              message: "抵扣币不能为空",
              type: "warning"
            });
            return;
          }
          this.form.image = this.$refs.uploadImg1.submitUpload()[0];
          this.form.projectImages = this.$refs.uploadImg2.submitUpload();
          //   console.log(this.form.image, this.form.projectImages);

          if (this.form.ensureContent) {
            this.form.ensureContent = this.form.ensureContent.join(",");
          } else {
            this.form.ensureContent = null;
          }

          // console.log(this.form)
          this.form.pBcId = this.form.cates.join("/");
          // this定义
          const tf = this.form;
          const datas = { ...this.form };
          if (datas.doctors) {
            datas.doctors = datas.doctors.map(String);
          } else {
            datas.doctors = null;
          }
          datas.discountsRange =
            datas.discountsRangeB + "~" + datas.discountsRangeE;
          if (this.$route.query.typeName) {
            this.createfn(datas);
          } else {
            this.updatafn(datas);
          }
        } else {
          this.form.ensureContent = this.form.ensureContent
            .split(",")
            .map(Number);
          this.form.doctors = this.form.doctors.map(Number);
          this.$message({
            message: "必填项不能为空",
            type: "warning"
          });
          return false;
        }
      });
    }
  }
};
</script>
<style scoped>
.app-container {
  padding: 0px !important;
}
</style>
